from __future__ import annotations

from datetime import date
from typing import Optional

from sqlmodel import Session, select

from .calc import calculate_next_anniversary_single
from .model import Reminder
from .notify import WeChatRobot


def update_reminder_fields(reminder: Reminder) -> None:
    result = calculate_next_anniversary_single(reminder.anniversary_date, reminder.is_lunar)
    if result:
        reminder.countdown_days = result["days_until_next_anniversary"]
        reminder.years_passed = result["next_occurrence"]
        reminder.next_anniversary = result["next_anniversary"]


def update_reminders(session: Session, reminder: Optional[Reminder] = None) -> None:
    """更新提醒中的倒数天数和周年数，并在接近时发送通知。"""
    if reminder is not None:
        reminders = [reminder]
    else:
        reminders = session.exec(select(Reminder)).all()

    for rem in reminders:
        update_reminder_fields(rem)
        if rem.countdown_days is not None and rem.countdown_days <= 3:
            try:
                WeChatRobot().send_text_message(f"距离 {rem.title} 还有 {rem.countdown_days} 天！")
            except Exception:
                pass
        session.add(rem)
    session.commit()


